<template>
  <el-card class="loop-controller" :header="title">
    <template #header>
      <div class="card-header">
        <span>{{ title }}</span>
        <div class="header-actions">
          <el-button 
            v-if="collapsible" 
            type="text" 
            @click="collapsed = !collapsed"
            class="collapse-btn"
          >
            <el-icon>
              <arrow-up v-if="!collapsed" />
              <arrow-down v-else />
            </el-icon>
          </el-button>
        </div>
      </div>
    </template>

    <div v-show="!collapsed" class="controller-content">
      <!-- 控制器类型选择 -->
      <div v-if="showTypeSelector" class="controller-type">
        <el-radio-group v-model="localConfig.type" @change="handleTypeChange">
          <el-radio 
            v-for="type in availableTypes" 
            :key="type.value" 
            :label="type.value"
            :value="type.value"
          >
            {{ type.label }}
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 次数循环配置 -->
      <div v-if="isCountLoop" class="loop-config count-loop">
        <div class="config-row">
          <label class="config-label">循环次数</label>
          <el-input-number
            v-model="localConfig.cycleIndex"
            :min="1"
            :max="10000"
            placeholder="循环次数"
            style="width: 200px;"
          />
        </div>
        <div class="config-row">
          <label class="config-label">循环间隔</label>
          <el-input-number
            v-model="localConfig.cycleInterval"
            :min="0"
            :max="999"
            placeholder="秒"
            style="width: 150px;"
          />
          <span class="unit">秒</span>
        </div>
      </div>

      <!-- For循环配置 -->
      <div v-if="isForLoop" class="loop-config for-loop">
        <div class="config-row">
          <label class="config-label">循环变量</label>
          <el-input
            v-model="localConfig.variableName"
            placeholder="定义变量名称"
            style="width: 180px;"
          />
          <span class="in-text">in</span>
          <el-input
            v-model="localConfig.variable"
            placeholder="变量，例如{{list}}"
            style="width: 200px;"
          />
        </div>
        <div class="config-row">
          <label class="config-label">循环间隔</label>
          <el-input-number
            v-model="localConfig.cycleInterval"
            :min="0"
            :max="999"
            placeholder="秒"
            style="width: 150px;"
          />
          <span class="unit">秒</span>
        </div>
      </div>

      <!-- While循环配置 -->
      <div v-if="isWhileLoop" class="loop-config while-loop">
        <WhileLoopConfig v-model="localConfig" />
      </div>

      <!-- 阶梯配置 -->
      <div v-if="showLadderConfig" class="ladder-config">
        <div class="ladder-header">
          <h4>阶梯配置</h4>
          <el-button type="primary" size="small" @click="addLadder">
            <el-icon><Plus /></el-icon>
            添加阶梯
          </el-button>
        </div>
        
        <div class="ladder-list">
          <div 
            v-for="(ladder, index) in localConfig.ladders" 
            :key="index"
            class="ladder-item"
          >
            <div class="ladder-index">{{ index + 1 }}</div>
            <div class="ladder-form">
              <el-input
                v-model="ladder.concurrencyNumber"
                placeholder="并发数"
                type="number"
                style="width: 120px;"
              />
              <el-input
                v-model="ladder.concurrencyStep"
                placeholder="递增步长"
                type="number"
                style="width: 120px;"
              />
              <el-input
                v-model="ladder.lastLong"
                placeholder="持续时间(秒)"
                type="number"
                style="width: 140px;"
              />
              <el-button 
                type="danger" 
                size="small" 
                @click="removeLadder(index)"
                :disabled="localConfig.ladders.length <= 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 高级选项 -->
      <div v-if="showAdvancedOptions" class="advanced-options">
        <el-divider content-position="left">
          <span class="divider-text">高级选项</span>
        </el-divider>
        
        <div class="config-row">
          <el-checkbox v-model="localConfig.breakOnError">
            遇到错误时终止执行
          </el-checkbox>
          <el-checkbox v-model="localConfig.logDetails">
            记录详细执行日志
          </el-checkbox>
        </div>
        
        <div v-if="isWhileLoop" class="config-row">
          <label class="config-label">最大执行时间</label>
          <el-input-number
            v-model="localConfig.maxDuration"
            :min="0"
            :max="7200"
            placeholder="秒"
            style="width: 150px;"
          />
          <span class="unit">秒 (0表示无限制)</span>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
import { Plus, Delete, ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import { DEFAULT_LADDER, DEFAULT_WHILE_CONFIG } from '@/constants/performanceConstants';
import WhileLoopConfig from './WhileLoopConfig.vue';

export default {
  name: 'LoopController',
  components: {
    Plus,
    Delete,
    ArrowUp,
    ArrowDown,
    WhileLoopConfig
  },
  
  props: {
    // 控制器配置
    modelValue: {
      type: Object,
      default: () => ({})
    },
    
    // 标题
    title: {
      type: String,
      default: '循环控制器'
    },
    
    // 是否显示类型选择器
    showTypeSelector: {
      type: Boolean,
      default: true
    },
    
    // 可用的循环类型
    availableTypes: {
      type: Array,
      default: () => [
        { label: '次数循环', value: 'count' },
        { label: 'for循环', value: 'for' },
        { label: 'while循环', value: 'while' }
      ]
    },
    
    // 是否显示阶梯配置
    showLadderConfig: {
      type: Boolean,
      default: false
    },
    
    // 是否显示高级选项
    showAdvancedOptions: {
      type: Boolean,
      default: true
    },
    
    // 是否可折叠
    collapsible: {
      type: Boolean,
      default: false
    }
  },
  
  emits: ['update:modelValue', 'type-change', 'config-change'],
  
  data() {
    return {
      collapsed: false,
      localConfig: {
        type: 'count',
        cycleIndex: '',
        cycleInterval: 0,
        variable: '',
        variableName: '',
        ladders: [{ ...DEFAULT_LADDER }],
        breakOnError: true,
        logDetails: false,
        maxDuration: 0,
        ...DEFAULT_WHILE_CONFIG,
        ...this.modelValue
      }
    }
  },
  
  computed: {
    /**
     * 是否为次数循环
     */
    isCountLoop() {
      return this.localConfig.type === 'count';
    },
    
    /**
     * 是否为for循环
     */
    isForLoop() {
      return this.localConfig.type === 'for';
    },
    
    /**
     * 是否为while循环
     */
    isWhileLoop() {
      return this.localConfig.type === 'while';
    }
  },
  
  watch: {
    modelValue: {
      handler(newValue) {
        this.localConfig = {
          ...this.localConfig,
          ...newValue
        };
      },
      deep: true,
      immediate: true
    },
    
    localConfig: {
      handler(newValue) {
        this.$emit('update:modelValue', { ...newValue });
        this.$emit('config-change', { ...newValue });
      },
      deep: true
    }
  },
  
  methods: {
    /**
     * 处理类型变化
     */
    handleTypeChange(newType) {
      // 重置特定类型的配置
      if (newType === 'count') {
        this.localConfig.cycleIndex = '';
        this.localConfig.variable = '';
        this.localConfig.variableName = '';
      } else if (newType === 'for') {
        this.localConfig.cycleIndex = '';
        this.localConfig.variable = '';
        this.localConfig.variableName = '';
      } else if (newType === 'while') {
        Object.assign(this.localConfig, DEFAULT_WHILE_CONFIG);
      }
      
      this.$emit('type-change', newType);
    },
    
    /**
     * 添加阶梯
     */
    addLadder() {
      this.localConfig.ladders.push({ ...DEFAULT_LADDER });
    },
    
    /**
     * 删除阶梯
     * @param {number} index - 阶梯索引
     */
    removeLadder(index) {
      if (this.localConfig.ladders.length > 1) {
        this.localConfig.ladders.splice(index, 1);
      }
    },
    
    /**
     * 验证配置
     * @returns {object} 验证结果
     */
    validate() {
      const errors = [];
      
      if (this.isCountLoop) {
        if (!this.localConfig.cycleIndex || this.localConfig.cycleIndex <= 0) {
          errors.push('请输入有效的循环次数');
        }
      } else if (this.isForLoop) {
        if (!this.localConfig.variableName) {
          errors.push('请输入循环变量名');
        }
        if (!this.localConfig.variable) {
          errors.push('请输入循环数据变量');
        }
      } else if (this.isWhileLoop) {
        if (this.localConfig.whileConditionType === 'variable') {
          if (!this.localConfig.whileLeftOperand) {
            errors.push('请输入左操作数');
          }
          if (!this.localConfig.whileRightOperand) {
            errors.push('请输入右操作数');
          }
        } else if (this.localConfig.whileConditionType === 'expression') {
          if (!this.localConfig.whileExpression) {
            errors.push('请输入条件表达式');
          }
        } else if (this.localConfig.whileConditionType === 'function') {
          if (!this.localConfig.whileFunctionName) {
            errors.push('请输入函数名称');
          }
        }
      }
      
      // 验证阶梯配置
      if (this.showLadderConfig) {
        this.localConfig.ladders.forEach((ladder, index) => {
          if (!ladder.concurrencyNumber || ladder.concurrencyNumber <= 0) {
            errors.push(`第${index + 1}个阶梯的并发数无效`);
          }
          if (!ladder.lastLong || ladder.lastLong <= 0) {
            errors.push(`第${index + 1}个阶梯的持续时间无效`);
          }
        });
      }
      
      return {
        isValid: errors.length === 0,
        errors
      };
    },
    
    /**
     * 重置配置
     */
    reset() {
      this.localConfig = {
        type: 'count',
        cycleIndex: '',
        cycleInterval: 0,
        variable: '',
        variableName: '',
        ladders: [{ ...DEFAULT_LADDER }],
        breakOnError: true,
        logDetails: false,
        maxDuration: 0,
        ...DEFAULT_WHILE_CONFIG
      };
    }
  }
};
</script>

<style scoped>
.loop-controller {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.collapse-btn {
  padding: 4px;
  margin: 0;
}

.controller-content {
  padding: 16px 0;
}

.controller-type {
  margin-bottom: 20px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.loop-config {
  margin-bottom: 20px;
}

.config-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 12px;
}

.config-label {
  min-width: 80px;
  font-weight: 500;
  color: #606266;
}

.unit {
  color: #909399;
  font-size: 14px;
}

.in-text {
  font-weight: 500;
  color: #409eff;
  margin: 0 8px;
}

.ladder-config {
  margin-bottom: 20px;
}

.ladder-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.ladder-header h4 {
  margin: 0;
  color: #409eff;
  font-size: 14px;
}

.ladder-list {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 16px;
}

.ladder-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 12px;
}

.ladder-item:last-child {
  margin-bottom: 0;
}

.ladder-index {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 500;
  flex-shrink: 0;
}

.ladder-form {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.advanced-options {
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}

.divider-text {
  color: #909399;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .config-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .config-label {
    min-width: auto;
  }
  
  .ladder-form {
    flex-direction: column;
    gap: 8px;
  }
  
  .ladder-form .el-input {
    width: 100% !important;
  }
}
</style>